<template>
  <Layout>
    <div class="brand-container">
      <!-- 功能入口区域 -->
      <div class="function-area">
        <el-button type="primary" @click="handleCreateBrand">新建品牌</el-button>
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入品牌名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 数据列表 -->
      <div class="data-table">
        <el-table
          :data="brandList"
          style="width: 100%"
          v-loading="loading"
          border
        >
          <el-table-column prop="name" label="品牌名称" width="200" />
          <el-table-column label="品牌图片" width="120">
            <template #default="scope">
              <el-image
                style="width: 60px; height: 60px"
                :src="scope.row.logo || 'https://via.placeholder.com/60'"
                fit="contain"
                :preview-src-list="scope.row.logo ? [scope.row.logo] : []"
              />
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="100" />
          <el-table-column prop="createdAt" label="创建时间" width="180" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 新建/编辑品牌弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑品牌' : '新增品牌'"
        width="500px"
        center
      >
        <el-form
          ref="formRef"
          :model="brandForm"
          :rules="formRules"
          label-width="80px"
        >
          <el-form-item label="品牌名称" prop="name">
            <el-input v-model="brandForm.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="备注" prop="description">
            <el-input v-model="brandForm.description" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="brandForm.sort" :min="1" :max="999" />
          </el-form-item>
          <el-form-item label="品牌图片" prop="logo">
            <el-upload
              class="logo-uploader"
              :auto-upload="false"
              list-type="picture-card"
              :limit="1"
              v-model:file-list="fileList"
              :on-change="handleFileChange"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">800*800 像素，仅支持JPG/PNG格式</div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search } from '@element-plus/icons-vue';
import Layout from '@/components/Layout.vue';
import { getBrandList, createBrand, updateBrand, deleteBrand } from '@/api/brand';

// 加载状态
const loading = ref(false);

// 品牌列表数据
const brandList = ref<any[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索关键字
const searchKeyword = ref('');

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();
const fileList = ref<any[]>([]);

// 品牌表单
const brandForm = reactive({
  objectId: '',
  name: '',
  logo: '',
  description: '',
  sort: 1,
  isShow: true
});

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { max: 50, message: '品牌名称不能超过50个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
};

// 加载品牌列表
const loadBrandList = async () => {
  loading.value = true;
  try {
    const response: any = await getBrandList();
    console.log('品牌数据:', response); // 添加日志，查看返回的数据结构
    
    // 直接使用response，不再尝试访问response.data
    brandList.value = response.results || [];
    total.value = response.count || 0;
  } catch (error) {
    console.error('获取品牌列表失败:', error);
    ElMessage.error('获取品牌列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadBrandList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadBrandList();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadBrandList();
};

// 处理新建品牌
const handleCreateBrand = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  resetForm();
  
  // 填充表单数据
  brandForm.objectId = row.objectId;
  brandForm.name = row.name;
  brandForm.logo = row.logo;
  brandForm.description = row.description || '';
  brandForm.sort = row.sort || 1;
  brandForm.isShow = row.isShow !== false;
  
  // 如果有logo，添加到文件列表
  if (row.logo) {
    fileList.value = [
      {
        name: 'logo',
        url: row.logo
      }
    ];
  }
  
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该品牌吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteBrand(row.objectId);
      ElMessage.success('删除成功');
      loadBrandList();
    } catch (error) {
      console.error('删除品牌失败:', error);
      ElMessage.error('删除品牌失败');
    }
  }).catch(() => {});
};

// 处理文件变更
const handleFileChange = (file: any) => {
  // 这里可以处理文件上传，例如调用API上传文件
  // 实际项目中，应该将文件上传到服务器，获取URL
  // 这里简单模拟一下
  brandForm.logo = URL.createObjectURL(file.raw);
};

// 重置表单
const resetForm = () => {
  brandForm.objectId = '';
  brandForm.name = '';
  brandForm.logo = '';
  brandForm.description = '';
  brandForm.sort = 1;
  brandForm.isShow = true;
  fileList.value = [];
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const data = {
          name: brandForm.name,
          logo: brandForm.logo,
          description: brandForm.description,
          sort: brandForm.sort,
          isShow: brandForm.isShow
        };
        
        if (isEdit.value) {
          await updateBrand(brandForm.objectId, data);
          ElMessage.success('编辑成功');
        } else {
          await createBrand(data);
          ElMessage.success('新增成功');
        }
        
        dialogVisible.value = false;
        loadBrandList();
      } catch (error) {
        console.error('保存品牌失败:', error);
        ElMessage.error('保存品牌失败');
      }
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadBrandList();
});
</script>

<style scoped>
.brand-container {
  padding: 0;
}

.function-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-box {
  width: 300px;
}

.data-table {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.logo-uploader {
  margin-bottom: 10px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 